<template>
  <canvas
    :canvas-id="canvasId"
    :id="canvasId"
    :style="`width:${opts.width}px;height:${opts.height}px;`"
    @touchstart="touchStart"
    @touchmove="touchMove"
    @touchend="touchEnd"
  ></canvas>
</template>

<script>
import uCharts from './u-charts.js'; // 直接引入js

export default {
  name: 'u-charts',
  props: {
    canvasId: { type: String, required: true },
    opts: { type: Object, required: true },
    chartData: { type: Object, required: true }
  },
  data() {
    return {
      chart: null
    };
  },
  watch: {
    chartData: {
      handler() {
        this.drawChart();
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.drawChart();
  },
  methods: {
    drawChart() {
      if (!uCharts) return;
      if (this.chart) this.chart = null;
      const opts = Object.assign({}, this.opts, this.chartData, {
        canvasId: this.canvasId
      });
      this.chart = new uCharts(opts);
    },
    touchStart(e) {
      if (this.chart && this.chart.touchLegend) this.chart.touchLegend(e);
      if (this.chart && this.chart.scrollStart) this.chart.scrollStart(e);
    },
    touchMove(e) {
      if (this.chart && this.chart.scroll) this.chart.scroll(e);
    },
    touchEnd(e) {
      if (this.chart && this.chart.scrollEnd) this.chart.scrollEnd(e);
      if (this.chart && this.chart.showToolTip) this.chart.showToolTip(e, {
        format: item => `${item.name}: ${item.data}`
      });
    }
  }
};
</script>